/*
 * create by Littleken at 2019/3/26 15:14
 */
package com.littleken.product.service.impl;

import com.littleken.product.dao.ProductInfoMapper;
import com.littleken.product.dto.CartDTO;
import com.littleken.product.enums.ProductStatusEnum;
import com.littleken.product.enums.ResultEnum;
import com.littleken.product.exception.SellException;
import com.littleken.product.model.ProductInfo;
import com.littleken.product.service.ProductService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import org.springframework.transaction.annotation.Transactional;
import java.util.List;

@Service
@Slf4j
public class ProductServiceImpl implements ProductService {

    @Autowired
    private ProductInfoMapper  mapper;

    @Override
    public List<ProductInfo> findUpAll() {
        return mapper.findByProductStatus(ProductStatusEnum.UP.getCode());
    }

    @Override
    public List<ProductInfo> findList(List<String> productIdList) {
        return mapper.findByProductIdIn(productIdList);
    }

    /**
     * 扣库存
     * @param cartDTOList 购物车List
     */
    @Override
    @Transactional
    public void decreaseStock(List<CartDTO> cartDTOList) {
        //查询库存是否足够
        for(CartDTO cartDTO : cartDTOList){
            ProductInfo productInfo = mapper.findById(cartDTO.getProductId()).get();
            if(productInfo == null ){
                //抛商品不存在异常
                throw new SellException(ResultEnum.PRODUCT_NOT_EXIST);
            }

            Integer result = productInfo.getProductStock() - cartDTO.getProductQuantity();
            if(result < 0){
                throw new SellException(ResultEnum.PRODUCT_STOCK_ERROR);
            }
            productInfo.setProductStock(result);
            mapper.save(productInfo);
        }
    }

    /**
     * 加库存
     * @return
     */
    @Transactional
    public void addStock(List<CartDTO> cartDTOList){
        for(CartDTO cartDTO : cartDTOList){
            ProductInfo productInfo = mapper.findById(cartDTO.getProductId()).get();
            if(productInfo == null ){
                //抛商品不存在异常
                throw new SellException(ResultEnum.PRODUCT_NOT_EXIST);
            }
            //todo:需要加锁优化并发
            Integer result = productInfo.getProductStock() + cartDTO.getProductQuantity();

            productInfo.setProductStock(result);
            mapper.save(productInfo);
        }
    }
}
